import { NextRequest, NextResponse } from 'next/server';
import UserModel from '@/models/user';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import pool from '@/utils/db';

// GET - 获取用户的所有技能
export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    
    // 获取用户的技能
    const skills = await UserModel.getSkills(userId);
    
    console.log('获取到的技能:', skills);
    
    return NextResponse.json(skills, { status: 200 });
  } catch (error) {
    console.error('获取技能错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}

// 添加新技能
export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    
    const { name, proficiency, description } = await request.json();

    // 验证输入
    if (!name || name.trim() === '') {
      return NextResponse.json(
        { error: '技能名称不能为空' },
        { status: 400 }
      );
    }

    // 检查proficiency是否在有效范围内(1-3)
    const proficiencyNum = Number(proficiency);
    if (isNaN(proficiencyNum) || proficiencyNum < 1 || proficiencyNum > 3) {
      return NextResponse.json(
        { error: '熟练度必须在1到3之间' },
        { status: 400 }
      );
    }

    // 检查是否已存在相同技能
    const [existingSkills] = await pool.query(
      'SELECT * FROM skills WHERE user_id = ? AND name = ?',
      [userId, name]
    );

    if ((existingSkills as any[]).length > 0) {
      return NextResponse.json(
        { error: '已存在相同名称的技能' },
        { status: 400 }
      );
    }

    // 插入新技能
    const [result] = await pool.query(
      'INSERT INTO skills (name, proficiency, description, user_id, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())',
      [name, proficiencyNum, description || '', userId]
    );

    // 获取新插入记录的ID
    const insertId = (result as any).insertId;

    // 查询新添加的技能详情
    const [newSkill] = await pool.query(
      'SELECT * FROM skills WHERE id = ?',
      [insertId]
    );

    return NextResponse.json({
      success: true,
      skill: (newSkill as any[])[0],
      message: '技能添加成功'
    });
  } catch (error) {
    console.error('添加技能失败:', error);
    return NextResponse.json(
      { error: '添加技能失败' },
      { status: 500 }
    );
  }
} 